package com.hailiao.beidou.message.data.message

import com.d10ng.common.calculate.isMobileNumber
import com.d10ng.common.calculate.isOnlyChSymbol
import com.d10ng.common.calculate.isOnlyCode
import com.d10ng.datelib.curTime
import com.hailiao.beidou.message.bd.Beidou
import com.hailiao.beidou.message.bd.constant.TextType
import com.hailiao.beidou.message.data.chat.ChatRepository
import com.hailiao.beidou.message.data.db.DB
import com.hailiao.beidou.message.data.db.constant.SendStatus
import com.hailiao.beidou.message.data.db.entity.MessageEntity
import com.hailiao.beidou.message.data.setting.SettingRepository

/**
 * 消息发送者
 * @Author d10ng
 * @Date 2024/3/6 14:10
 */
object MessageSender {

    private val messageDao by lazy { DB.instant.messageDao() }

    /**
     * 发送消息
     * @param number String
     * @param content String
     */
    suspend fun send(number: String, content: String) {
        val temp: String
        val type: TextType
        when {
            content.isOnlyCode() -> {
                // 代码
                temp = content
                type = TextType.CODE
            }
            content.isOnlyChSymbol() -> {
                // 汉字和全角符号
                temp = content
                type = TextType.CHINESE
            }
            else -> {
                // 混合
                if (number.isMobileNumber()) {
                    temp = content.toFullWidth()
                    type = TextType.CHINESE
                } else {
                    temp = content
                    type = TextType.MIX
                }
            }
        }
        // 创建消息写入数据库
        val time = curTime
        val message = MessageEntity(
            number = number,
            createTime = time,
            sendTime = time,
            isSendOut = true,
            status = SendStatus.SENDING.value,
            content = content,
            isLocation = false,
            location = null
        )
        val id = messageDao.insert(message)
        message.id = id
        ChatRepository.updateBy(message)
        // 执行发送
        message.status =
            if (Beidou.sendMessage(SettingRepository.protoFlow.value, number, temp, type)) {
                SendStatus.SUCCESS.value
            } else {
                SendStatus.FAILED.value
            }
        // 更新消息状态
        messageDao.update(message)
        ChatRepository.updateBy(message)
    }

    /**
     * 将字符串中的半角符号转换为全角符号
     */
    private fun String.toFullWidth(): String {
        val sb = StringBuilder()
        for (c in this) {
            when (c.code) {
                in 33..126 -> sb.append((c.code + 65248).toChar())
                32 -> sb.append("　")
                else -> sb.append(c)
            }
        }
        return sb.toString()
    }
}